﻿using Logger.Service.Interface;
using WebSocketApi.CacheManager;

namespace WebSocketApi.Extensions;


/// <summary>
/// Socket用户管理
/// </summary>
public class SocketUserManagerService : ISocketUserManagerService
{
    private readonly ICacheContext _cacheContext;
    private readonly ILoggerContext _logger;
    private readonly IConfiguration _configuration;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="cacheContext"></param>
    /// <param name="logger"></param>
    /// <param name="configuration"></param>
    public SocketUserManagerService(ICacheContext cacheContext, ILoggerContext logger, IConfiguration configuration)
    {
        _cacheContext = cacheContext;
        _logger = logger;
        _configuration = configuration;
    }

    /// <summary>
    /// 保存连接用户
    /// </summary>
    /// <param name="userInfo"></param> 
    /// <returns></returns>
    public async Task AddUser(SocketUserInfo userInfo)
    {
        try
        {
            var cacheKey = $"{userInfo.UserAccount}_verify";
            var cacheTimeExpired = _configuration.GetSection("SocketApi:HistoryNoticeCacheDay").Value ?? "7";
            _cacheContext.SetCache(cacheKey, userInfo, DateTime.Now.AddDays(Convert.ToInt32(cacheTimeExpired)));

        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            _logger.Error("保存连接用户", e);
        }
    }

    /// <summary>
    /// 删除用户(断开连接，超时清理)
    /// </summary>
    /// <param name="userAccount"></param>
    /// <returns></returns>
    public async Task RemoveUser(string userAccount)
    {
        try
        {
            var cacheKey = $"{userAccount}_verify";
            _cacheContext.Remove(cacheKey);
            await Task.CompletedTask;
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            _logger.Error("RemoveUser", e);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="userAccount"></param>
    /// <returns></returns>
    public async Task<SocketUserInfo> GetUserInfo(string userAccount)
    {
        try
        {
            var cacheKey = $"{userAccount}_verify";
            await Task.CompletedTask;
            return _cacheContext.GetCache<SocketUserInfo>(cacheKey);
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            _logger.Error("GetUserInfo", e);
            return null;
        }
    }

}
